// 用户注册
function register() {
    const username = document.getElementById('registerUsername').value;
    const email = document.getElementById('registerEmail').value;
    const password = document.getElementById('registerPassword').value;

    if (!username || !email || !password) {
        alert('请填写完整信息');
        return;
    }

    const users = JSON.parse(localStorage.getItem('users')) || [];
    if (users.some(user => user.username === username)) {
        alert('用户名已存在');
        return;
    }

    users.push({ username, email, password });
    localStorage.setItem('users', JSON.stringify(users));
    alert('注册成功，请登录');
}

// 用户登录
function login() {
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;

    const users = JSON.parse(localStorage.getItem('users')) || [];
    const user = users.find(u => u.username === username && u.password === password);

    if (user) {
        localStorage.setItem('currentUser', username);
        window.location.href = 'index.html';
    } else {
        alert('用户名或密码错误');
    }
}

// 用户退出
function logout() {
    localStorage.removeItem('currentUser');
    window.location.href = 'pages/user.html';
}

// 页面加载时检查登录状态
window.addEventListener('load', () => {
    const currentUser = localStorage.getItem('currentUser');
    const welcomeSection = document.getElementById('welcomeSection');
    const authSection = document.getElementById('authSection');

    if (currentUser) {
        if (welcomeSection) {
            welcomeSection.style.display = 'block';
            document.getElementById('welcomeMessage').textContent = `欢迎，${currentUser}！`;
        }
        if (authSection) {
            authSection.style.display = 'none';
        }
    } else {
        if (welcomeSection) {
            welcomeSection.style.display = 'none';
        }
        if (authSection) {
            authSection.style.display = 'block';
        }
    }
});
